<?php
namespace haoleke\utils;
/**
 * @author  云想网络科技（盐城）有限公司
 */
class Tree
{
    /**
     * 将数组转化成树
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     * @author:ge(gexiuhua@live.com)
     */
    public static function list2Tree($list, $pk = 'id', $pid = 'parent_id', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                if (empty($list[$key]['child'])) {
                    $list[$key]['child'] = null;
                }
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];

                        if ($parent == null) {
                            $parent[$child][] = null;
                        } else {
                            $parent[$child][] =& $list[$key];
                        }
                    }
                }
            }
        }
        return $tree;
    }

    private static $formatTree; //用于树型数组完成递归格式的全局变量

    public static function getTree($list,$title = 'title')
    {
        /* 获取所有分类 */
        $list = self::toFormatTree($list,$title);
        return $list;
    }

    public static function toFormatTree($list, $title = 'name', $pk = 'id', $pid = 'parent_id', $root = 0)
    {
        $list = self::list2Tree($list, $pk, $pid, '_child', $root);
        self::$formatTree = array();
        self::_toFormatTree($list, 0, $title);
        return self::$formatTree;
    }

    private static function _toFormatTree($list, $level = 0, $title = 'name')
    {
        foreach ($list as $key => $val) {
            $tmp_str = "|";
            $tmp_str .= str_repeat("—", $level * 2);
            $val['level'] = $level;
            $val['title_show'] = $level == 0 ? $val[$title] . " " : $tmp_str . $val[$title] . " ";
            // $val['title_show'] = $val['id'].'|'.$level.'级|'.$val['title_show'];
            if (!array_key_exists('_child', $val)) {
                array_push(self::$formatTree, $val);
            } else {
                $tmp_ary = $val['_child'];
                unset($val['_child']);
                array_push(self::$formatTree, $val);
                self::_toFormatTree($tmp_ary, $level + 1, $title); //进行下一层递归
            }
        }

        return;
    }
}